import axios from "axios";
import { config } from "../config/index";
import { resp } from "../utils/res";
import md5 from "md5";
import { getaccessLogger } from "../logger";
import { Context } from "koa";
import moment from "moment";
class chatgpt {
  async chatgpt(ctx: Context) {
    let zhword = ctx.request.body.word;
    console.log("====================================");
    console.log(zhword);
    console.log("====================================");
    var flag = true;
    const key = config.ChatGpt;
    const BaiDu_appid = config.BaiDu_appid;
    const BaiDu_key = config.BaiDu_key;
    const salt = Math.random();
    const zhToen = async (word: string) => {
      const sign = md5(BaiDu_appid + word + salt + BaiDu_key);
      const params = {
        q: word,
        from: "zh",
        to: "en",
        salt,
        appid: BaiDu_appid,
        sign,
      };
      try {
        let fyres = await axios.get(
          "http://api.fanyi.baidu.com/api/trans/vip/translate",
          { params }
        );
        if (fyres.data.error_code == "58000") {
          console.log("翻译异常，百度服务器ip需要重置");
          console.log("====================================");
          console.log(fyres.data);
          console.log("====================================");
        } else {
          console.log(`关键词${zhword}翻译正常`);
          return fyres.data.trans_result[0].dst as any;
        }
      } catch (error) {
        console.log("====================================");
        console.log("翻译失败", error);
        console.log("====================================");
      }
    };

    // const enTozh = async (word: string) => {
    //   const sign = md5(BaiDu_appid + word + salt + BaiDu_key);
    //   const params = {
    //     q: word,
    //     from: "en",
    //     to: "zh",
    //     salt,
    //     appid: BaiDu_appid,
    //     sign,
    //   };
    //   try {
    //     let fyres = await axios.get(
    //       "http://api.fanyi.baidu.com/api/trans/vip/translate",
    //       { params }
    //     );

    //     return fyres.data.trans_result[0] as any;
    //   } catch (error) {
    //     if (error) {
    //       console.log("====================================");
    //       console.log("翻译失败", error);
    //       console.log("====================================");
    //     }
    //   }
    // };

    if (flag) {
      flag = false;
      try {
        let res = await axios.post(
          "https://api.openai.com/v1/completions",
          {
            prompt: zhword,
            temperature: 0.7,
            max_tokens: 2048,
            model: "text-davinci-003",
          },
          {
            headers: {
              "Content-Type": "application/json",
              Authorization: `Bearer ${key}`,
            },
          }
        );
        if (res) {
          var str = res.data.choices[0].text.replace(/\r|\n/gi, "  /  ");
          getaccessLogger.info(
            "搜索记录",
            `time:${moment(Date.now()).format(
              "YYYY-MM-DD HH:mm:ss"
            )}-word:${zhword}-info:${str}`
          );
          //   var str = res.data.choices[0].text;
          try {
            let ffres = await zhToen(str);
            resp.success(ctx, { src: ffres, dst: str });
            flag = true;
          } catch (error) {
            if (error) {
              flag = true;
            }
          }
        }
      } catch (error: any) {
        // console.log("====================================");
        // console.log(error);
        // console.log("====================================");
        resp.error(ctx, "请求错误，请稍后再试");
        flag = true;
      }
    } else {
      resp.error(ctx, "请求繁忙，请稍后再试");
    }
  }
}
const cgt = new chatgpt();
export default cgt;
